<template>
  <Section>
    <div class="flex items-center justify-center">
      <LoginSVG />
      <ZForm
        :initial-values="initialValues"
        :rules="rules"
        #="{ cBinds, errors, resetForm }"
        @success="onSuccess"
      >
        <ZFormItem name="email" label="电子邮件" :errors="errors">
          <ZInput v-bind="cBinds.email" />
        </ZFormItem>
        <ZFormItem name="password" label="密码" :errors="errors">
          <ZInput type="password" v-bind="cBinds.password" />
        </ZFormItem>
        <ZFormItem name="code" label="验证码" :errors="errors">
          <ZInput v-bind="cBinds.code" />
          <img
            :src="captchaImg"
            alt="验证码"
            @click="captchaImg = `/captcha?t=${randStr()}`"
          />
        </ZFormItem>
        <div class="flex items-center gap-4 p-4">
          <ZButton class="btn-primary" :loading="isFetching">
            <template #icon>
              <span class="icon-[uil--sign-in-alt] h-6 w-6"></span>
            </template>
            登录
          </ZButton>
          <ZButton type="reset" class="btn-secondary" @click="resetForm()">
            <template #icon>
              <span class="icon-[uil--redo] h-6 w-6"></span>
            </template>
            重置
          </ZButton>
        </div>
      </ZForm>
    </div>
  </Section>
</template>
<script setup lang="ts">
import { SubmissionContext } from "vee-validate";
import { z } from "zod";
import { ApiResponse, useApiFetch } from "@/composables/useApiFetch";
import { randStr } from "@/components/utils";
import { useUserStore } from "@/stores/user";

const initialValues = import.meta.env.DEV
  ? {
      email: "34857766@qq.com",
      password: "123456",
      code: "unk!",
    }
  : {
      email: "",
      password: "",
      code: "",
    };

const rules = z.object({
  email: z.string().email({ message: "不是合法的电子邮件地址" }),
  password: z
    .string()
    .min(6, { message: "至少需要6个字符" })
    .max(20, { message: "最多包含20个字符" }),
  code: z.string().length(4, { message: "验证码必须是4个字符" }),
});

const { isFetching, data, post } = useApiFetch<ApiResponse>("/login", {
  immediate: false,
});
const router = useRouter();
const userStore = useUserStore();
const onSuccess = async (
  values: any,
  { resetForm, setErrors }: SubmissionContext,
) => {
  // 发起 post 请求
  await post(values).json().execute();

  if (data.value?.success) {
    // 登录成功，将用户信息保存至全局状态
    userStore.login(data.value.object);
    // 重置表单
    resetForm();
    // 跳转我的首页
    router.push({ name: "my.index" });
  } else {
    // 设置错误信息
    if (data.value?.errors) setErrors(data.value.errors);
  }
};

const captchaImg = ref("/captcha");
</script>
